import React, {useEffect, useState} from 'react';
import {View, Dimensions, StyleSheet} from 'react-native';
import {SideBar} from '../components';
import StickerDataSQL from '../db';
import {DB_ST} from '../utils/DBFields';
import NativeFileUtils from 'rtn-supernote-plugin-core/src/module/NativeFileUtils';
import {renameFunGroup, saveSticker, stickerGroupAdd} from '../utils/StickerUtils';
import NativeEvent from 'rtn-supernote-plugin-core/src/module/NativeEvent';
import i18n from '../i18n';
import {findNextEm} from '../utils/jsUtils';

const StickerCreatePage = ({changeEvent}) => {
  const [stickerName, setStickerName] = useState('');
  const [stickerDefaultName, setStickerDefaultName] = useState('');
  const [stickerGroups, setStickerGroups] = useState([]);
  const [stickerGroup, setStickerGroup] = useState(null);
  const [screenWidth, setScreenWidth] = useState(
    Dimensions.get('window').width,
  );
  const [screenHeight, setScreenHeight] = useState(
    Dimensions.get('window').height,
  );

  useEffect(() => {
    _getStickerGroupList();
  }, []);

  /*
   * 查询全部的贴纸库
   * */
  const _getStickerGroupList = async () => {
    try {
      const {data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_GROUP_UPDATE_ST,
        [],
      );
      console.log(data, 'setStickerGroupsetStickerGroup');
      setStickerGroups([...data]);
      if (data?.length > 0) {
        const res = await renameFunGroup(
          i18n.t('title.newColl') + ' 1_sticker',
          DB_ST.SELECT_NAME_ST,
        );
        setStickerName(res);
        setStickerGroup(data[0]);
      } else {
        setStickerName(i18n.t('title.newColl') + ' 1_sticker 1');
        setStickerGroup({
          id: 'new_create_group',
          name: i18n.t('title.newColl'),
        });
      }
    } catch (error) {
      console.error('Error fetching sticker groups:', error);
    }
  };

  /*
   *添加贴纸库
   * */
  const _stickerGroupAdd = async groupName => {
    const {code, data} = await stickerGroupAdd(groupName);
    console.log(data, 'addDataaddDataaddDataaddData');
    if (code === 200) {
      const makeDir = await NativeFileUtils.makeDir(data?.path);
      console.log(makeDir, 'makeDirmakeThDir');
      setStickerGroup({
        name: groupName,
        path: data?.path,
        thumb_sticker: '',
        id: data?.id,
      });
      if (stickerGroups?.length < 1) {
        _saveSticker(data);
      } else {
        await _getStickerGroupList();
        return {
          name: groupName,
          path: data?.path,
          thumb_sticker: '',
          id: data?.id,
        };
      }
    }
  };

  const _saveSticker = async (data = null) => {
    try {
      const res = await saveSticker(
        data || stickerGroup,
        stickerName || stickerDefaultName,
      );
      if (res) {
        setStickerName('');
        setStickerDefaultName('');
        await StickerDataSQL.db_fun(DB_ST.UPDATE_GROUP_STICKER_UPDATE_ST, [
          Date.now(),
          stickerGroup?.id,
        ]);
        await _getStickerGroupList();
        await NativeEvent.onStop();
      }
    } catch (e) {
      console.log(e);
    }
  };
  const _onItemPress = async item => {
    if (item.id === 'new_create_group') {
      if (stickerGroups?.length > 49) {
        return;
      }
      setStickerGroup(item);
    } else {
      const {code, data} = await StickerDataSQL.db_fun(
        DB_ST.SELECT_STICKER_GROUP_ID_ST,
        [item?.id],
      );
      if (data?.length > 199) {
        return;
      } else {
        setStickerGroup(item);
        setStickerDefaultName(
          findNextEm(data, item?.name + '_sticker', ite => ite.name),
        );
      }
    }
  };

  return (
    <View style={styles.flexAlign}>
      <SideBar
        stickerGroups={stickerGroups}
        screenWidth={screenWidth}
        screenHeight={screenHeight}
        from={'base'}
        onItemPress={async data => {
          await _onItemPress(data);
        }}
        stickerGroupId={stickerGroup?.id}
      />
    </View>
  );
};

export default StickerCreatePage;
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    flex: 1,
  },
  flexCenter: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  flexAlign: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  flexCenterSpace: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
});
